<template>
  <div class="login-container">
    <el-form :model="form" label-width="auto" style="max-width: 600px">
      <el-form-item label="用户名">
        <el-input v-model="form.username" />
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="form.password" type="password" />
      </el-form-item>

      <el-button type="primary" @click="login" style="width: 100%">登录</el-button>
    </el-form>
  </div>
</template>

<script setup>
import { reactive } from 'vue'
import { useRouter } from 'vue-router'
import { loginApi } from '@/request/api'
import { ElMessage } from 'element-plus'

const router = useRouter()
const form = reactive({
  username: '',
  password: '',
})

const login = () => {
  if (form.username && form.password) {
    loginApi(form).then((res) => {
      console.log(res)

      if (res) {
        ElMessage({
          message: res.data.message,
          type: 'success',
        })
        localStorage.setItem('username', res.data.data.username)
        localStorage.setItem('token', res.data.data.token)
        localStorage.setItem('roles', res.data.data.roles)
        router.push('/home')
      }
    })
  } else {
    ElMessage.error('用户名和密码不能为空')
  }
}
</script>

<style scoped>
.login-container {
  position: fixed;
  width: 300px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
